package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.service.BusinessRuleService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.BusinessRuleSetWhiteListDTO;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/5/8 11:09
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX+"/script/businessRule")
public class BusinessRuleScriptController {

    @Resource
    private ProBaseConfig proBaseConfig;

    @Resource
    private BusinessRuleService businessRuleService;

    @RequestMapping(value = "/setWhiteList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String explains(@RequestBody @Valid BusinessRuleSetWhiteListDTO businessRuleSetWhiteListDTO, BindingResult br) throws XbbException {
        XbbResponse<ScriptVO> response;
        if ( br.hasErrors() ) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if (!proBaseConfig.getXbbCode().equals(businessRuleSetWhiteListDTO.getXbbCode())) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                ScriptVO detailTabScriptVO = businessRuleService.setWhiteList(businessRuleSetWhiteListDTO);
                response = new XbbResponse<>(detailTabScriptVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

}
